package cn.com.blueInfo.core.baseService.init;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Log4j2
@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ResourceLoader resourceLoader;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Override
    public void run(String... args) throws Exception {
        // 根据驱动类名判断数据库类型
        String dbType = getDbType(driverClassName);
        log.info("当前数据库类型：{}", dbType);
        // 根据不同数据库执行对应的表创建逻辑
        switch (dbType) {
            case "mysql":
                createTablesForMysql();
                break;
            case "sqlserver":
                createTablesForSqlServer();
                break;
            case "oracle":
                createTablesForOracle();
                break;
            default:
                throw new RuntimeException("不支持的数据库类型：" + driverClassName);
        }
        log.info("数据库初始化完成");
    }

    private void createTablesForMysql() throws IOException {
        try {
            // 执行一个简单的 SQL 查询来验证连接
            jdbcTemplate.queryForObject("SELECT 1", Integer.class);
            log.info("MySQL 连接验证成功");
        } catch (Exception e) {
            log.error("MySQL 连接验证失败: " + e.getMessage());
            // 这里可以选择抛出异常，使应用启动失败
            throw new RuntimeException("MySQL 连接验证失败", e);
        }
        Resource resource = resourceLoader.getResource("classpath:config/application.yml");
        if (resource.exists()) {
            String sqlContent = FileCopyUtils.copyToString(
                    new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)
            );
            System.out.println(sqlContent);
        }
    }

    private void createTablesForSqlServer() {

    }

    private void createTablesForOracle() {

    }

    // 判断数据库类型
    private String getDbType(String driverClassName) {
        if (driverClassName.contains("mysql")) return "mysql";
        if (driverClassName.contains("sqlserver")) return "sqlserver";
        if (driverClassName.contains("oracle")) return "oracle";
        return "unknown";
    }

}
